<template>
  <div class="bind_email">
    <div class="container-fluid">
      <div class="row">
        <div class="col-md-2 col-md-offset-5 col-xs-6 col-xs-offset-3">
          <img src="../../assets/logo1.png" class="text-center" style="width: 50%;margin: 25% 25% 0 25%;">
          <h3 class="text-center">绑定邮箱</h3>
        </div>
      </div>
      <div class="row">
        <div class="col-md-6 col-md-offset-3">
          <van-form @submit="onSubmit" >
            <van-field
                v-model="email"
                name="邮箱地址"
                label="邮箱地址"
                placeholder="请输入用于找回密码的邮箱地址"
                :rules="[{ pattern: emailpattern,required: true, message: '请输入正确的邮箱地址' }]"
            />
            <div style="margin: 16px;">
              <van-button :loading="logloading" loading-text="绑定中..." block round size="large" type="info" native-type="submit">绑定</van-button>
            </div>
          </van-form>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import {emailBind} from "../../utils/api";
import qs from "qs";

export default {
  name: "BindEmail",
  data(){
    return {
      email:'',
      logloading:false,
      emailpattern:/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,})$/,
      beforfrom:''
    }
  },
  methods:{
    onSubmit(){
      if(!localStorage.getItem('userToken')){
        this.$notify({
          title: '警告',
          message: '请先登录',
          type: 'error'
        });
        this.$router.replace("/login");
      }else{
        this.logloading=true
        emailBind(qs.stringify({
          email:this.email
        })).then(res=>{
          this.logloading=false
          if(res.status==200){
            this.$notify({
              title: '成功',
              message: res.msg,
              type: 'success'
            });
            this.$store.commit('setUseremail',this.email);
            if(this.beforfrom=="/user/personal" ){
              this.$router.go(-1);
            }else if(this.beforfrom!=="/register" && this.beforfrom!=="/login"){
              this.$router.go(-2); //返回上级路由
            }
            this.$router.replace("/") //如果没有返回，我们就指定跳转到首页
          }else{
            this.$notify({
              title: '警告',
              message: res.msg,
              type: 'error'
            });
          }
        })
      }
    }
  },
  beforeRouteEnter (to, from, next) {
    next(vm => {
      vm.beforfrom = from.path
    })
  },
}
</script>

<style scoped>

</style>
